#include "light_point.h"
#include "ray.h"
#include "scene.h"

#include <iostream>

PointLight::PointLight(Scene *scene) : Light(scene)
{
  std::cout << "Point Light Created" << std::endl;
}

PointLight::~PointLight()
{

}

void PointLight::loadAttributes(std::istream &inData)
{
  m_pos.loadAttributes(inData);
  inData >> m_color.r >> m_color.g >> m_color.b;
  inData >> m_intensity;

  inData.ignore();
}

Color PointLight::computeColor(Collision c, double &reflectK) const
{
  Ray collisionToLight;
  collisionToLight.pos = c.pos;
  collisionToLight.dir = m_pos - c.pos;

  Collision lightIntersection = m_scene->intersectScene(collisionToLight);
  if (lightIntersection.isValid)
  {
    if ((lightIntersection.pos - m_pos).magnitude() < 
        collisionToLight.dir.magnitude())
    {
      return Color();
    }
  }

  /* Cosine Shading */
  Coordinate lightNormal = collisionToLight.dir;
  lightNormal.normalize();

  double lightK = lightNormal.dot(c.normal);
  if (lightK <= 0)
  {
    return Color();
  }

  c.src.normalize();
  Coordinate directReflectRay = c.normal + c.normal - c.src;
  directReflectRay = c.normal + directReflectRay;
  directReflectRay.normalize();
  reflectK = directReflectRay.dot(lightNormal);

  Color resultColor = m_color * m_intensity / collisionToLight.dir.dot();
  return resultColor * lightK;
}
